<?php

function cmd_del($id)
{
   $sql = new db();
   $req = 'DELETE commande, ligne_commande FROM commande, ligne_commande WHERE commande.Id_Commande='.$id.' AND ligne_commande.Id_Commande='.$id;
   $sql->query($req);
   header("Location:".ABS_PATH.ROOT."?page=Entrepot/Commande");   
}

function cmd_dep($id, $_POST)
{
   $sql = new db();
   $req = "INSERT INTO couts VALUES ('".$id."', '".$_POST['valeur_stock']."', '".$_POST['valeur_cfixes']."', '".$_POST['valeur_prepa']."', '0')";
   $sql->query($req);
   $req = "UPDATE commande SET Etat='d', Last_Mod=".time()." WHERE Id_Commande=".$id;
   $sql->query($req);
   header("Location:".ABS_PATH.ROOT."?page=Entrepot/Commande");   
}

function cmd_val($id)
{
	$sql = new db();
	$req = "UPDATE commande SET Etat='s', Last_Mod=".time()." WHERE Id_Commande=".$id;
	$sql->query($req);
	$req = "SELECT li.Id_colis, li.Quantite, st.Quantite_Dispo, co.GLN_Entrepot FROM stocker AS st, commande AS co, ligne_commande AS li WHERE li.Id_Commande=".$id." AND co.Id_commande=".$id." AND st.GLN_Entrepot =".$_SESSION['login']." AND st.Id_colis = li.Id_colis";
	$sql->query($req);
	$array = array();
	while ($res = $sql->fetch_array())
		$array[] = $res;
	foreach($array AS $res)
	{
		$req = "UPDATE stocker SET Quantite_Dispo=(Quantite_dispo - '".$res['Quantite']."') WHERE Id_colis ='" .$res['Id_colis']."' AND GLN_Entrepot =".$_SESSION['login'];
		$sql->query($req);
		$req = "SELECT * FROM historique_entrepot WHERE Id_colis ='".$res['Id_colis']."' AND Date ='".date("Y-m-d")."' AND GLN_Entrepot =".$_SESSION['login'];
		$sql->query($req);
		if ($sql->num_rows() > 0)
			$req = "UPDATE historique_entrepot SET GLN_Entrepot=".$res['GLN_Entrepot'].", Id_colis='".$res['Id_colis']."', Quantite =(".$res['Quantite_Dispo']."-".$res['Quantite']."), Date=NOW() WHERE Id_colis ='".$res['Id_colis']."'";
		else
			$req = "INSERT INTO historique_entrepot VALUES ('".$res['GLN_Entrepot']."' , '".$res['Id_colis']."' , ('".$res['Quantite_Dispo']."'-'".$res['Quantite']."') , NOW())";
	$sql->query($req);
	}
		$req = "UPDATE preparation SET date_fin_effective = NOW() WHERE Id_Commande=".$id;
		$sql->query($req);
   header("Location:".ABS_PATH.ROOT."?page=Entrepot/Commande");  
}

if (isset($_GET['id']) && !empty($_GET['id']) && isset($_GET['action']) && !empty($_GET['action']))
{
 switch ($_GET['action'])
 {
  case 'Delete':
   cmd_del($_GET['id']);
   break;
  case 'Valider':
   cmd_val($_GET['id']);
   break;
  case 'Depart':
   cmd_dep($_GET['id'], $_POST);
   break;
 }
}

 ?>